package com.beiding.jsonanalyzer.querylink;

import com.beiding.jsonanalyzer.flow.BranchNode;
import com.beiding.jsonanalyzer.flow.ValueNode;
import com.beiding.jsonanalyzer.flow.flowevents.*;

import java.util.HashSet;
import java.util.Set;

/**
 * 节点去重
 */
public class DistinctQueryLinkNode<W extends ValueNode> extends ComputeNode<W> {

    public DistinctQueryLinkNode(QueryLinkNode<W> pre) {
        super(pre);
    }

    @Override
    protected void bindByComputeNode(BranchNode<W> preResult, BranchNode<W> newBranchNode) {

        Set<W>[] o = new Set[]{null};

        ComputeNodeUtils.bindBaseEvent(preResult, newBranchNode);

        //批开始
        preResult.onDataEvent(BatchStartEvent.eventType(), event -> {
            newBranchNode.signDataEvent(event);
            o[0] = new HashSet<>();
        });

        //批开始
        preResult.onDataEvent(BatchEndEvent.eventType(), event -> {
            newBranchNode.signDataEvent(event);
            o[0] = null;
        });

        preResult.onDataEvent(DataNodeEvent.eventType(), event -> {

            if (!o[0].contains(event.getData())) {
                o[0].add(event.getData());
                newBranchNode.signDataEvent(event);
            }

        });

    }
}
